//
//  ComposeTableViewController.swift
//  新浪微博
//
//  Created by 李国伟 on 15/12/6.
//  Copyright © 2015年 李国伟. All rights reserved.
//

import UIKit

class ComposeController: UIViewController {

    //关闭控制器
    @objc private func colseController() {
        textView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //发布图片
    @objc private func pickerImage(){
        
        textView.resignFirstResponder()
        if picturePicker.view.frame.height > 0{
            return
        }
        
        //更改约束
        picturePicker.view.snp_updateConstraints { (make) -> Void in
            make.left.equalTo(view)
            make.right.equalTo(view)
            make.bottom.equalTo(view)
            make.height.equalTo(view.bounds.height * 0.6)
        }
        
        textView.snp_remakeConstraints { (make) -> Void in
            make.top.equalTo(navagtionBar.snp_bottom)
            make.bottom.equalTo(picturePicker.view.snp_top)
            make.left.equalTo(view)
            make.right.equalTo(view)
        }
        
        //用动画更改约束
        UIView.animateWithDuration(0.5) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    //发布微博
    @objc private func setMessage (){
      let text = textView.appendEmojiString()
      let image = picturePicker.pictures.last
        NetworkTools.sharedTools.sendStatus(text, image: image ) { (result, error) -> () in
        
            if error != nil {
                print(error)
                return
            }
        
          self.colseController()
      }

    }
    
    //点击表情弹出键盘
    @objc private func selectEmoticon() {
       
        textView.resignFirstResponder()
        textView.inputView = textView.inputView == nil ? emojiView : nil
        textView.becomeFirstResponder()
    }
    
    //textview的代理方法
    func textViewDidChange(textView: UITextView) {
        navagtionBar.items![0].rightBarButtonItem?.enabled = textView.hasText()
        palcehoderLabel.hidden = textView.hasText()
    }
    
    //执行监听方法
    @objc private func keyboardChange (n : NSNotification) {
        
        let rect = (n.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        let offset = -UIScreen.mainScreen().bounds.height + rect.origin.y
        //从键盘获取的curve为7
        let curve = (n.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).integerValue
        //设置动画的的时长
        let duration = (n.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        
        //更新控件位置
        toolBar.snp_updateConstraints{ (make) -> Void in
            make.bottom.equalTo(view).offset(offset)
        }
        
        UIView.animateWithDuration(duration) { () -> Void in
            //如果设置了curve 为7 那么设置所有的动画时间将会不其作用
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve)!)
            self.view.layoutIfNeeded()
        }
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        textView.becomeFirstResponder()
    }
    
    //销毁通知
    deinit{
       NSNotificationCenter.defaultCenter().removeObserver(self)
    }
 
    
    //懒加载控件
    private lazy var picturePicker = PictureSelectController()
    private lazy var navagtionBar = UINavigationBar()
    private lazy var toolBar: UIToolbar = UIToolbar()
    private lazy var palcehoderLabel:UILabel = UILabel()
    private lazy var textView = UITextView()
    private lazy var emojiView: EmotionView = EmotionView {[weak self] (emotion) -> () in
        self?.textView.insertEmoji(emotion)
    }
}

//MARK:  懒加载控件设置属性
extension ComposeController:UITextViewDelegate {
    
    //设置子控件，并添加约束
    private func setupUI(){
        automaticallyAdjustsScrollViewInsets = false
        view.addSubview(navagtionBar)
        view.addSubview(toolBar)
        view.addSubview(textView)
        navagtionBar.backgroundColor = UIColor.redColor()
        addChildViewController(picturePicker)
        view.insertSubview(picturePicker.view, belowSubview: toolBar)

        
        navagtionBar.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(view)
            make.left.equalTo(view)
            make.right.equalTo(view)
            make.height.equalTo(64)
        }
        
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(view)
            make.right.equalTo(view)
            make.bottom.equalTo(view)
            make.height.equalTo(44)
        }
        
        textView.snp_makeConstraints { (make) -> Void in
//            make.top.equalTo(self.snp_topLayoutGuideBottom)
            make.top.equalTo(navagtionBar.snp_bottom)
            make.bottom.equalTo(toolBar.snp_top)
            make.left.equalTo(view)
            make.right.equalTo(view)
        }
        
        picturePicker.view.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(view)
            make.bottom.equalTo(view)
            make.right.equalTo(view)
            make.height.equalTo(view.bounds.height * 0)
        }
        
        prepareForNavagtionBar()
        prepareForTextView()
        prepareForToolBar()
    }
    
    //MARK:  设置顶部导航栏
    private func prepareForNavagtionBar () {
        navagtionBar.tintColor = UIColor.orangeColor()
        let item = UINavigationItem()
        navagtionBar.items?.append(item)
        item.leftBarButtonItem = UIBarButtonItem(title: "返回", style: .Plain, target: self, action: "colseController")
        item.rightBarButtonItem = UIBarButtonItem(title: "发布", style: .Plain, target: self, action: "setMessage")
        item.rightBarButtonItem?.enabled = false
        item.titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 36))
        
        //顶部label
        let topLabel = UILabel(title: "我的微博", fontsize: 16, color: UIColor.darkGrayColor())
        let name = UserAccountViewModel.shareModel.account?.screen_name ?? ""
        let bottomLabel = UILabel(title: name, fontsize: 14, color: UIColor.lightGrayColor())
        item.titleView?.addSubview(topLabel)
        item.titleView?.addSubview(bottomLabel)
        
        topLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(item.titleView!)
            make.left.equalTo(item.titleView!)
            make.right.equalTo(item.titleView!)
        }
        
        bottomLabel.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(item.titleView!)
            make.left.equalTo(item.titleView!)
            make.right.equalTo(item.titleView!)
        }
    }
    
    //MARK:
    private func prepareForTextView(){
        textView.font = UIFont.systemFontOfSize(18)
        textView.keyboardDismissMode = .OnDrag
        textView.alwaysBounceVertical = true
        textView.delegate = self
        
        //设置占位label
        view.addSubview(palcehoderLabel)
        palcehoderLabel.text = "分享点新鲜事..."
        palcehoderLabel.textColor = UIColor.lightGrayColor()
        palcehoderLabel.font = UIFont.systemFontOfSize(18)
        //刀哥自己测试的
        palcehoderLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView).offset(8)
            make.left.equalTo(textView).offset(5)
        }
    }
    
    //MARK:  设置tabbar栏
    private func prepareForToolBar() {
        
        //解决最后一个按钮的灰度问题
        toolBar.backgroundColor = UIColor(white: 0.8, alpha: 1)
        
        let itemSettings = [["imageName": "compose_toolbar_picture","actionName":"pickerImage"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "actionName": "selectEmoticon"],
            ["imageName": "compose_addbutton_background"]]
        
        var items = [UIBarButtonItem]()
        
        items.append(UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil))
        for dict in itemSettings {
            //警告怎么消除？待测试
           let button = UIButton(imageNamed: dict["imageName"]!, backImageNamed: "")
            
            
            if let actionName = dict["actionName"] {
               button.addTarget(self, action: Selector(actionName), forControlEvents: .TouchUpInside)
            }
            
            
            let item = UIBarButtonItem(customView: button)
            items.append(item)
            items.append(UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil))
        }
        
        toolBar.items = items
    }
}